﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;

namespace CoreShop.PrintService
{
    public class JsPrinter : PrinterBaseIP
    {
        public string printerIP { get; set; }


        /// <summary>
        /// 打开打印机
        /// </summary>
        /// <param name="printername"></param>
        /// <returns></returns>
        public Boolean OpenNetSev()
        {
            if (m_Inited > 0)
            {
                return true;
            }
            string ip = printerIP;
            var ret = InitNetSev();
            return ret;
        }

        /// <summary>
        /// 关闭打印机
        /// </summary>
        /// <param name="printername"></param>
        /// <returns></returns>
        public Boolean CloseNetPor()
        {
            if (m_Inited < 0) return true;
            ushort fs1 = (ushort)m_Inited;
            CloseNetPor(fs1);
            return true;
        }

        /// <summary>
        /// 连接打印机
        /// </summary>
        /// <param name="printername"></param>
        /// <returns></returns>
        public int ConnectNetPort(string ipAddr)
        {
            return ConnectNetPort(IpStringToUint(ipAddr), 9100, 5000);
        }

        /// <summary>
        /// 打开打印机
        /// </summary>
        /// <param name="printername"></param>
        /// <returns></returns>
        public int ReadFromNetPort()
        {
            string content = " ";
            if (m_Inited < 0) return m_Inited;
            byte[] textBytes = Encoding.Default.GetBytes(content);
            byte[] bts = new byte[1];
            Array.Copy(textBytes, 0, bts, 0, textBytes.Length);

            ushort fs1 = (ushort)m_Inited;
            byte[] data = { 0x1D, 0x6B, (byte)1 };
            byte[] send = new byte[3 + content.Length + 1];
            ushort fsSize = (ushort)send.Length;
            int ret = WriteToNetPort(fs1, send, fsSize);
            return ret;
            //return ReadFromNetPort(fs1, send, fsSize);
        }

        public uint IpStringToUint(string ipString)
        {
            var ipAddress = IPAddress.Parse(ipString);
            var ipBytes = ipAddress.GetAddressBytes();
            var ip = (uint)ipBytes[0] << 24;
            ip += (uint)ipBytes[1] << 16;
            ip += (uint)ipBytes[2] << 8;
            ip += (uint)ipBytes[3];
            return ip;
        }
    }
}
